//
//  OauthViewController.swift
//  weiboSwift1.0
//
//  Created by xuNick on 16/4/19.
//  Copyright © 2016年 NN. All rights reserved.
//

import UIKit

import SVProgressHUD


    let WB_APP_KEY:String = "4117371138"

    let WB_REDIRECT_URI = "https://www.baidu.com/"

    let WB_APP_SECRET = "697bfcf5ae5d77af9bc775963900beeb"

class OauthViewController: UIViewController {
    
    
  override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor(white: 237/255, alpha: 1)
        
        title = "登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "clickCloseButton")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "clickAutoFill")

    }
    
    
    override func loadView() {
        view = webView
         let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APP_KEY)&redirect_uri=\(WB_REDIRECT_URI)"
        let url:NSURL = NSURL(string: urlString)!
        let request: NSURLRequest = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }
    
    //点击
    @objc private func clickCloseButton(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func clickAutoFill(){
        let jsString = "document.getElementById('userId').value='812448369@qq.com';document.getElementById('passwd').value='2652510asaa'"
        self.webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    //  MARK: - 懒加载控件

    lazy private var webView:UIWebView = {
    let view = UIWebView()
        view.delegate = self
        return view
    }()
    
//    private func loadAccessToken(code: String){
//        
//         let urlString = "https://api.weibo.com/oauth2/access_token"
//        
//        
//        let params = [
//            "client_id": WB_APP_KEY,
//            "client_secret": WB_APP_SECRET,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri": WB_REDIRECT_URI
//        ]
//    NetworkingTool.shareWorkTools.request(RequestMethod.Post, urlString: urlString, parameters: params) { (reponseObject, error) -> () in
//        if error != nil{
//            print(error)
//            return
//        }
//        
//        guard let dict = reponseObject as? [String : AnyObject] else{
//            print("数据加载不正确")
//            return
//        }
//        let account = UserAccount(dict: dict)
//        print(account)
//        
//        self.loadUserInfo(account)
//        
//        }
//        
//    }
//    
//    
//    private func loadUserInfo(account: UserAccount){
//        // 请求地址
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        
//        // 请求参数
//        let params = [
//            "access_token": account.access_token ?? "",
//            "uid": account.uid ?? ""
//        ]
//        
//        // 发送请求
//        NetworkingTool.shareWorkTools.request(urlString: urlString, parameters: params) { (responseObject, error) -> () in
//            
//            if error != nil {
//                SVProgressHUD.showErrorWithStatus("网络错误")
//                return
//            }
//            // 判断返回数据是否是字典
//            guard let dict = responseObject as? [String: AnyObject] else {
//                print("后台返回的数据格式不对")
//                return
//            }
//            // 如果等于前面是可选值的话，就使用 as? 如果是必选值，就使用 as!
//            account.name = dict["name"] as? String
//            account.avatar_large = dict["avatar_large"] as? String
//            
//            print(account)
//        // #warning TODO: 保存登录信息
//            self.saveUserInfo(account)
//        //跳转控制器
//        }
//    }
//    
//    private func saveUserInfo(account:UserAccount){
//        //沙盒路径
//        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
//        //保存.
//        NSKeyedArchiver.archiveRootObject(account, toFile: path)
//    }
//    
//    private func accountInSanbox() -> UserAccount? {
//        // 测试解档
//        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
//        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount
//        return result
//    }
//
    
    
    
    
    
    
    
}

extension OauthViewController:UIWebViewDelegate{
    
    // MARK: -  webview代理
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 取到请求里面的 url
        guard let url = request.URL else {
            return false
        }
        
        // 判断 url 的地址是否以回调页开头
        if url.absoluteString.hasPrefix(WB_REDIRECT_URI) {
            // 代表是以回调开头
            // 从 url 里面截取 授权码
            // query 代表url后面的参数 （ ? 后面的字符）
            
            // containsString ：是否包含某个字符串
            if let q = url.query where q.containsString("code="){
                // 截取 授权码
                let code = q.substringFromIndex("code=".endIndex)
                
                
                // 通过 code 获取 accessToken
                UserAccountViewModel.shareUserAccountViewModel.loadAccessToken(code, finished: { (issuccess) -> () in
                    self.dismissViewControllerAnimated(true, completion: { () -> Void in
                         NSNotificationCenter.defaultCenter().postNotificationName(HMChangeRootVCNotification, object: nil)
                    })
                })

            }
            return false
        }
        
        // 判断是否是回调页，如果是回调页，返回 false
        
        return true
    }
}









